//
//  ZZEditInfoController.m
//  QQplayground
//
//  Created by zhangxy on 2018/8/7.
//  Copyright © 2018年 zhang. All rights reserved.
//

#import "ZZEditInfoController.h"
#import "ZZEditUserCell.h"
#import "MyFavListController.h"
#import "UIView+Border.h"
#import <BRPickerView.h>
#import "AVFoundation/AVFoundation.h"
#import "AudioToolBox/AudioToolBox.h"

@interface ZZEditInfoController () <UITableViewDelegate, UITableViewDataSource,ImagePickerDelegate,ZZEditUserCellDelegate>{
    
    CGPoint        contentoffset;// 记录list的偏移量
    
    BRProvinceModel *checkProvince;
    BRCityModel *checkCity;
    int remoton;
    
    NSArray *arr;
    
}

@property (nonatomic, strong) UIImageView *imgAvatar;

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, copy) NSArray *titleArr;
@property (nonatomic, copy) NSDictionary *countDict;

@property (nonatomic, copy) ZTextView *tempTextView;

@property (nonatomic, strong) NSString *string;
@property (nonatomic, strong) NSArray *datas1;
@property (nonatomic, strong) NSArray *datas2;
@property (nonatomic, strong) NSArray *datas3;
@property (nonatomic, strong) AVAudioPlayer *playMusic;//背景音乐

@end

@implementation ZZEditInfoController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"个人资料";
    
    [self setNavigationBar];
    
    UIButton *rightBtn = [self createButton];
    [rightBtn setFrame:CGRectMake(0, 0, 56, 26)];
    [rightBtn setTitle:@"保存" forState:0];
    [rightBtn setBackgroundColor:UIColorFromRGBAlpha(TextWhiteColor, 0.3)];
    [rightBtn setTitleColor:UIColor.whiteColor forState:0];
    rightBtn.layer.cornerRadius = 8.0f;
    rightBtn.layer.masksToBounds = YES;
    [rightBtn addTarget:self action:@selector(saveuser:) forControlEvents:UIControlEventTouchUpInside];
   
     self.navigationItem.rightBarButtonItem =  [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    
    
    self.navigationController.navigationBarHidden = NO;
    // Do any additional setup after loading the view.
    
    
    arr = @[@"单身",@"求交往",@"暗恋中",@"暧昧中",@"热恋中"];
    
    
    if(_tempUser == nil){
        _tempUser = [UserUtil getUser];
    }
    
    _titleArr = @[];
    remoton = [arr indexOfObject:convertToString(_tempUser.user_emotion)] + 1;
    
    [self.view addSubview:self.tableView];
    
    
    UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
    gestureRecognizer.numberOfTapsRequired = 1;
    gestureRecognizer.cancelsTouchesInView = NO;
    [_tableView addGestureRecognizer:gestureRecognizer];
    
    [self refreshData];
}


-(void)refreshData{
    NSString *birday=@"";
//    if(convertToString(_tempUser.birth_year).length > 0 && [_tempUser.birth_year intValue]>0 && convertToString(_tempUser.birth_month).length > 0 && convertToString(_tempUser.birth_day).length > 0){
//        if([_tempUser.birth_day intValue] < 10){
//            _tempUser.birth_day = [NSString stringWithFormat:@"0%@",_tempUser.birth_day];
//        }
//        if([_tempUser.birth_month intValue] < 10){
//            _tempUser.birth_month = [NSString stringWithFormat:@"0%@",_tempUser.birth_month];
//        }
//        birday = [NSString stringWithFormat:@"%@-%@-%@",_tempUser.birth_year,_tempUser.birth_month,_tempUser.birth_day];
//    }
     birday = [NSString stringWithFormat:@"%@-%@-%@",_tempUser.birth_year,_tempUser.birth_month,_tempUser.birth_day];
    _titleArr = @[@{@"title":@"昵称",@"icon":@"收藏 头像",@"code":@"1",@"value":convertToString(_tempUser.user_name)},
                  @{@"title":@"性别",@"icon":@"收藏 图片",@"code":@"2",@"value":convertIntToString((int)_tempUser.user_gender)},
                  @{@"title":@"QQ",@"icon":@"收藏 签名",@"code":@"4",@"value":convertToString(_tempUser.user_qq)},
                  @{@"title":@"生日",@"icon":@"收藏 网名",@"code":@"5",@"value":convertToString(birday)},
                  @{@"title":@"城市",@"icon":@"收藏 分组",@"code":@"6",@"value":convertToString(_tempUser.user_region)},
                  @{@"title":@"感情状态",@"icon":@"收藏 壁纸",@"code":@"3",@"value":convertToString(_tempUser.user_emotion)},
                  @{@"title":@"个性签名",@"icon":@"收藏 自拍",@"code":@"7",@"value":convertToString(_tempUser.user_sign)}];
    
    [_tableView reloadData];
    
}

-(void)saveuser:(UIButton*)btn{
    
    if(checkProvince != nil && checkCity!=nil){
        
    }
    
    NSDictionary *params = @{@"session_uid":convertToString(_tempUser.user_id),
                             @"user_name":convertToString(_tempUser.user_name),
                             @"user_gender":convertIntToString((int)_tempUser.user_gender),
                             @"user_qq":convertToString(_tempUser.user_qq),
                             @"birth_year":convertToString(_tempUser.birth_year),
                             @"birth_month":convertToString(_tempUser.birth_month),
                             @"birth_day":convertToString(_tempUser.birth_day),
                             @"user_emotion":convertIntToString(remoton),
                             @"user_sign":convertToString(_tempUser.user_sign),
//                             @"area_province":checkProvince ? checkProvince.code : @"",
//                             @"area_city":checkCity?checkCity.code :@""
                             };
    if(checkProvince != nil && checkCity!=nil){
        params = @{@"session_uid":convertToString(_tempUser.user_id),
                   @"user_name":convertToString(_tempUser.user_name),
                   @"user_gender":convertIntToString((int)_tempUser.user_gender),
                   @"user_qq":convertToString(_tempUser.user_qq),
                   @"birth_year":convertToString(_tempUser.birth_year),
                   @"birth_month":convertToString(_tempUser.birth_month),
                   @"birth_day":convertToString(_tempUser.birth_day),
                   @"user_emotion":convertIntToString(remoton),
                   @"user_sign":convertToString(_tempUser.user_sign),
                @"area_province":checkProvince ? checkProvince.code : @"",
                @"area_city":checkCity?checkCity.code :@""
                   };
    }
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [NetworkUtil POST:API_Setuserinfo parameters:params success:^(id responseObject, NSDictionary *dict) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
        if(_ZZCommitResult){
            _ZZCommitResult(0,dict[@"msg"]);
            
        }
        [self backAction];
        [PopUtil showMessage:@"修改成功"];
    } failure:^(NSError *error, NSString *message) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [PopUtil showMessage:message];
    }];
}



- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        [_tableView registerNib:[UINib nibWithNibName:@"ZZEditUserCell" bundle:nil] forCellReuseIdentifier:@"ZZEditUserCell"];
        
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.tableHeaderView = [self createTableHeaderView];
    }
    return _tableView;
}

-(UIView *) createTableHeaderView{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 151)];
    headerView.userInteractionEnabled = YES;
    [headerView setBackgroundColor:UIColor.whiteColor];
    [headerView addBottomBorderWithColor:UIColorFromRGB(BgLineColor) andWidth:1.0f];
    
    _imgAvatar = [self createImageView];
    [_imgAvatar sd_setImageWithURL:[NSURL URLWithString:convertToString([UserUtil getUser].user_avatar)] placeholderImage:[UIImage imageNamed:@"default_image"]];
    [_imgAvatar setFrame:CGRectMake((ScreenWidth-85)/2, 20, 85, 85)];
    _imgAvatar.layer.cornerRadius = 85/2;
    _imgAvatar.layer.masksToBounds = YES;
    _imgAvatar.userInteractionEnabled = YES;
    [headerView addSubview:_imgAvatar];
    
    
    UIButton *btn =[self createButton];
    [btn setTitle:@"更换头像" forState:0];
    [btn setTitleColor:UIColorFromRGB(BgTitleColor) forState:0];
    [btn setFrame:CGRectMake(0, 115, ScreenWidth, 21)];
    [btn addTarget:self action:@selector(changeAvatar) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:btn];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeAvatar)];
    [_imgAvatar addGestureRecognizer:tap];
    
    
    return headerView;
}

-(void)changeAvatar{
    [[ImagePickerUtil defaultPicker] startPickerWithController:self title:@"更换头像"];
}


- (void)imagePickerDidFinishedWithInfo:(NSDictionary *)info image:(UIImage *) thumIamge file:(NSURL *) url type:(ImagePickerDelegateType) type{
    if(thumIamge){
        NSData *data = UIImageJPEGRepresentation(thumIamge,0.3);
        
        [ImageUploadUtil uploadImage:data api:API_Setavatar  param:@{@"session_uid":[UserUtil getUser].user_id} callback:^(NSString *imageurl, NSDictionary *videoDict, NSString *message) {
            NSLog(@"%@",videoDict);
            
            if(videoDict){
                User *user = [UserUtil getUser];
                user.user_avatar = videoDict[@"image_url"];
                [UserUtil saveUser:user];
                [self->_imgAvatar sd_setImageWithURL:[NSURL URLWithString:convertToString([UserUtil getUser].user_avatar)] placeholderImage:[UIImage imageNamed:@"default_image"]];
            }else{
                [PopUtil showMessage:message];
            }
            
        }];
    }
}

#pragma mark - tableView delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _titleArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.1f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44.0f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return [[UIView alloc] init];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return [[UIView alloc] init];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"ZZEditUserCell";
    ZZEditUserCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[ZZEditUserCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.indexPath = indexPath;
    cell.tempModel = _tempUser;
    cell.delegate = self;
    NSDictionary *item = _titleArr[indexPath.row];
    
    [cell dataToView:item];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSDictionary *item = _titleArr[indexPath.row];
    NSLog(@"%@",item);
    
    int code = [item[@"code"] intValue];
    if (code == 2){
        
    }
    // 生日
    if(code == 5){
        
        NSString *birday=@"";
        if(convertToString(_tempUser.birth_year).length > 0 && [_tempUser.birth_year intValue]>0 && convertToString(_tempUser.birth_month).length > 0 && convertToString(_tempUser.birth_day).length > 0){
            if([_tempUser.birth_day intValue] < 10){
                _tempUser.birth_day = [NSString stringWithFormat:@"0%@",_tempUser.birth_day];
            }
            if([_tempUser.birth_month intValue] < 10){
                _tempUser.birth_month = [NSString stringWithFormat:@"0%@",_tempUser.birth_month];
            }
            birday = [NSString stringWithFormat:@"%@-%@-%@",_tempUser.birth_year,_tempUser.birth_month,_tempUser.birth_day];
//            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//            // this is imporant - we set our input date format to match our input string
//            // if format doesn't match you'll get nil from your string, so be careful
//            [dateFormatter setDateFormat:@"yyyy-MM-dd"];
//            curDate = [dateFormatter dateFromString:birday];
        }
        
        [BRDatePickerView showDatePickerWithTitle:@"" dateType:BRDatePickerModeDate defaultSelValue:birday minDate:nil maxDate:[NSDate date] isAutoSelect:NO themeColor:UIColorFromRGB(BgTitleColor) resultBlock:^(NSString *selectValue) {
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            // this is imporant - we set our input date format to match our input string
            // if format doesn't match you'll get nil from your string, so be careful
            [dateFormatter setDateFormat:@"yyyy-MM-dd"];
            NSDate *date = [dateFormatter dateFromString:selectValue];
            self.tempUser.birth_day = convertIntToString((int)date.getDay);
            self.tempUser.birth_year = convertIntToString((int)date.getYear);
            self.tempUser.birth_month = convertIntToString((int)date.getMonth);
            [self refreshData];
            
        } cancelBlock:^{
            
        }];
    }
    // 城市
    if(code == 6){
        [BRAddressPickerView showAddressPickerWithShowType:BRAddressPickerModeCity defaultSelected:@[@10,@3] isAutoSelect:NO themeColor:UIColorFromRGB(BgTitleColor) resultBlock:^(BRProvinceModel *province, BRCityModel *city, BRAreaModel *area) {
            checkProvince = province;
            checkCity = city;
            self.tempUser.user_region = [NSString stringWithFormat:@"%@ %@",province.name,city.name];
            [self refreshData];
        } cancelBlock:^{
            
        }];
    }
    // 感情状态
    if(code == 3){
        [BRStringPickerView showStringPickerWithTitle:@"" dataSource:arr defaultSelValue:nil isAutoSelect:NO themeColor:UIColorFromRGB(BgTitleColor) resultBlock:^(id selectValue) {
            self.tempUser.user_emotion = selectValue;
            if ([@"单身" isEqualToString:selectValue]){
                NSLog(@"单身");
                NSString *path = [[NSBundle mainBundle]pathForResource:@"singleDog"  ofType:@"mp3"];
                NSURL *url = [NSURL fileURLWithPath:path];
                self.playMusic = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
                [self.playMusic setNumberOfLoops:0];
                [self.playMusic prepareToPlay];
                [self.playMusic play];
            }
            
            remoton = [arr indexOfObject:selectValue] + 1;
            
            [self refreshData];
        } cancelBlock:^{
            
        }];
    }
}

-(void)onValueChange:(NSInteger)type data:(User *)tempUser{
    _tempUser = tempUser;
}


-(void)didKeyboardWillShow:(NSIndexPath *)indexPath view1:(ZTextView *)textview{
    _tempTextView = textview;
    
    //获取当前cell在tableview中的位置
    CGRect rectintableview=[_tableView rectForRowAtIndexPath:indexPath];
    
    //获取当前cell在屏幕中的位置
    CGRect rectinsuperview = [_tableView convertRect:rectintableview fromView:[_tableView superview]];
    
    contentoffset = _tableView.contentOffset;
    
    if ((rectinsuperview.origin.y+50 - _tableView.contentOffset.y)>200) {
        
        [_tableView setContentOffset:CGPointMake(_tableView.contentOffset.x,((rectintableview.origin.y-_tableView.contentOffset.y)-150)+  _tableView.contentOffset.y) animated:YES];
        
    }
}


- (void) hideKeyboard {
    if(!is_null(_tempTextView)){
        [_tempTextView resignFirstResponder];
        _tempTextView = nil;
    }else{
        [self allHideKeyBoard];
    }
    
    if(contentoffset.x != 0 || contentoffset.y != 0){
        // 隐藏键盘，还原偏移量
        [_tableView setContentOffset:contentoffset];
    }
}


- (void)allHideKeyBoard
{
    for (UIWindow* window in [UIApplication sharedApplication].windows)
    {
        for (UIView* view in window.subviews)
        {
            [self dismissAllKeyBoardInView:view];
        }
    }
}

-(BOOL) dismissAllKeyBoardInView:(UIView *)view
{
    if([view isFirstResponder])
    {
        [view resignFirstResponder];
        return YES;
    }
    for(UIView *subView in view.subviews)
    {
        if([self dismissAllKeyBoardInView:subView])
        {
            return YES;
        }
    }
    return NO;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
